package com.chao.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chao.entity.*;
import com.chao.entity.Class;
import com.chao.interceptor.StudentAddUtils;
import com.chao.mapper.StudentMapper;
import com.chao.service.*;
import com.chao.service.impl.ClassServiceImpl;
import com.chao.service.impl.ScoreServiceImpl;
import com.chao.service.impl.StudentServiceImpl;
import com.chao.utils.TypeConversion;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Controller
public class StudentController {

    @Autowired
    StudentServiceImpl studentService;
    @Autowired
    ScoreServiceImpl scoreService;
    @Autowired
    CourseService courseService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    MajorService majorService;
    @Autowired
    ClassService classService;

    Course course;

    // 搜索功能
    @GetMapping("/search")
    @ResponseBody
    public Msg student_search(@RequestParam String search) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("s_Id", search).or().eq("s_name", search);
        Page<Student> studentPage = new Page<>(1, 100);
        Page<Student> page = studentService.getBaseMapper().selectPage(studentPage, wrapper);
        List<Student> students = page.getRecords();
        for (Student s : students) {
            Department dept = departmentService.getOne(new QueryWrapper<Department>().eq("d_id", s.getSDepartment()));
            Major major = majorService.getOne(new QueryWrapper<Major>().eq("m_id", s.getSMajor()));
            Class clazz = classService.getOne(new QueryWrapper<Class>().eq("c_id", s.getSClass()));
            s.setDName(dept.getDName());
            s.setMName(major.getMName());
            s.setCName(clazz.getCName());
        }
        return Msg.success().add("page", page).add("students", students);
    }

    // 条件查询
    @GetMapping("/student_queryById")
    @ResponseBody
    public Msg student_query(Student student) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("s_id", student.getSId());
        Student studentOne = studentService.getOne(wrapper);

        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("d_id", studentOne.getSDepartment());
        Department department = departmentService.getOne(departmentQueryWrapper);

        QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
        majorQueryWrapper.eq("m_id", studentOne.getSMajor());
        Major major = majorService.getOne(majorQueryWrapper);

        QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();
        classQueryWrapper.eq("c_id", studentOne.getSClass());
        Class clazz = classService.getOne(classQueryWrapper);

        studentOne.setDName(department.getDName());
        studentOne.setMName(major.getMName());
        studentOne.setCName(clazz.getCName());

        return Msg.success().add("student", studentOne);
    }

    // 更新数据
    @PutMapping("/student/{sId}")
    @ResponseBody
    public Msg class_update(@PathVariable String sId,
                            @Valid Student student) {
        student.setSId(sId);
        student.setSDate(new Date());
        studentService.updateById(student);
        return Msg.success();
    }


    // 批量删除 和 单个删除一起
    @DeleteMapping("/student/{sIds}")
    @ResponseBody
    public Msg student_delete(@PathVariable String sIds) {
        if (sIds.contains("-")) {
            String[] strings = sIds.split("-");
            studentService.removeBatchByIds(Arrays.asList(strings));
        } else {
            studentService.removeById(sIds);
        }
        return Msg.success();
    }


    // 实现添加功能
    @PostMapping("/student")
    @ResponseBody
    public Msg student_add(@Valid Student student) {
        student.setSDate(new Date());
        String dept = StudentAddUtils.IntegerToString(student.getSDepartment());
        String major = StudentAddUtils.IntegerToString(student.getSMajor());
        String clazz = StudentAddUtils.IntegerToString(student.getSClass());
        int year = new Date().getYear() - 100;
        String prev = year + dept + major + clazz;

        String sId = studentService.selectMaxId(prev);
        if (sId == null) {
            sId = "01";
            student.setSId(prev + sId);
        } else {
            int parseInt = Integer.parseInt(sId.substring(sId.length() - 2)) + 1;
            String s = StudentAddUtils.IntegerToString(parseInt);
            student.setSId(prev + s);
        }
        studentService.save(student);
        return Msg.success();
    }

    @GetMapping("/student")
    @ResponseBody
    public Msg student(@RequestParam(defaultValue = "1") Integer pn) {
        Page<Student> page = new Page<>(pn, 5);
        Page<Student> studentPage = studentService.getBaseMapper().selectALL(page);
        List<Student> students = studentPage.getRecords();
        return Msg.success().add("page", page).add("students", students);
    }

    // 去 页面
    @GetMapping("/student_table")
    public String class_table() {
        return "student/student_table";
    }

    /**
     *
     */

    @GetMapping("/student_score_table")
    public String student_score(@RequestParam(defaultValue = "1") Integer pn,
                                Model model) {
        Page<Score> page = new Page<>(pn, 5);
        Page<Score> scorePage = scoreService.selectAll(page);
        List<Score> scores = scorePage.getRecords();
        model.addAttribute("scores", scores);
        model.addAttribute("page", page);
        return "student/student_score";
    }

    // 添加学生成绩
    @PostMapping("/student_score")
    public String student_score_add(@Valid Score score,
                                    @RequestParam Integer pn,
                                    RedirectAttributes ra) {
//        scoreService
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("c_name", score.getCName());
        Course course = courseService.getOne(courseQueryWrapper);

        score.setCId(course.getCId());
        score.setSDate(new Date());

        scoreService.save(score);

        ra.addAttribute("pn", pn);
        return "redirect:/student_score_table";
    }

    // 删除成绩
    @DeleteMapping("/deleteScore")
    public String score_delete(@RequestParam String sIds,
                               @RequestParam String cNames,
                               @RequestParam String sTerms,
                               @RequestParam Integer pn,
                               RedirectAttributes ra) {
        QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();

        if (sIds.contains("-")) {
            String[] sIds_split = sIds.split("-");
            String[] cName_split = cNames.split("-");
            String[] sTerm_split = sTerms.split("-");
            for (int i = 0; i < sIds_split.length; i++) {
                courseQueryWrapper.clear();
                courseQueryWrapper.eq("c_name", cName_split[i]);
                course = courseService.getOne(courseQueryWrapper);

                scoreQueryWrapper.clear();
                scoreQueryWrapper.eq("s_term", sTerm_split[i])
                        .eq("c_id", course.getCId()).eq("s_id", sIds_split[i]);
                scoreService.remove(scoreQueryWrapper);
            }
        } else {
            courseQueryWrapper.clear();
            scoreQueryWrapper.clear();
            courseQueryWrapper.eq("c_name", cNames);
            course = courseService.getOne(courseQueryWrapper);
            scoreQueryWrapper.eq("s_term", sTerms)
                    .eq("c_id", course.getCId()).eq("s_id", sIds);
            scoreService.remove(scoreQueryWrapper);
        }

        ra.addAttribute("pn", pn);
        return "redirect:/student_score_table";
    }

    // 修改成绩
    @PutMapping("/updateScore")
    public String score_update(Score score,
                               @RequestParam Integer pn,
                               RedirectAttributes ra) {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("c_name", score.getCName());
        course = courseService.getOne(courseQueryWrapper);
        score.setCId(course.getCId());
        score.setSDate(new Date());

        UpdateWrapper<Score> scoreUpdateWrapper = new UpdateWrapper<>();
        scoreUpdateWrapper.eq("s_id", score.getSId());
        scoreUpdateWrapper.eq("c_id", course.getCId());
        scoreUpdateWrapper.eq("s_term", score.getSTerm());
        scoreService.update(score, scoreUpdateWrapper);
        ra.addAttribute("pn", pn);
        return "redirect:/student_score_table";
    }

}
